package system

import (
	"errors"
	"example.com/m/v2/global"
	"example.com/m/v2/model"
	"example.com/m/v2/model/request"
	"fmt"
)

type UserService struct{}

var UserServ = new(UserService)

func (u *UserService) Login(username, password string) (*model.SysUser, error) {
	if nil == global.GVA_DB {
		return nil, fmt.Errorf("db not init")
	}
	var user model.SysUser

	err := global.GVA_DB.Where("Account = ?", username).Find(&user).Error

	if err == nil {
		errors.New("密码错误")
		//验证密码
		//	if ok := utils.BcryptCheck(u.Password, user.Password); !ok {
		//			return nil, errors.New("密码错误")
		//		}
	}

	return &user, err
}

func (u *UserService) Register(username, password string) (interface{}, error) {
	return nil, nil
}

func (u *UserService) Logout() error {
	return nil
}

func (u *UserService) GetUserById(id int) (*model.SysUser, error) {
	var user model.SysUser
	db := global.GVA_DB.Model(&model.SysUser{})
	err := db.Where("ID = ?", id).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

// GetUserList
//
//	@Description:
//	@receiver u
//	@param: 查询条件
//	@return: 用户列表
//	@return: 总数
//	@return error
func (u *UserService) GetUserList(q request.UserQueryModel) (list []model.SysUser, total int64, err error) {
	db := global.GVA_DB.Model(&model.SysUser{})

	//db = db.Where("", "")
	if q.Phone != "" {
		db = db.Where("phone LIKE ?", "%"+q.Phone+"%")
	}
	err = db.Count(&total).Error

	if err != nil {
		return
	}

	err = db.Limit(q.PageSize).Offset(q.PageSize * (q.Page - 1)).Find(&list).Error

	return list, total, err
}

func (u *UserService) Create(entity *model.SysUser) (err error) {
	db := global.GVA_DB.Model(&model.SysUser{})

	err = db.Create(&entity).Error

	if err != nil {
		return err
	}
	return
}
